package gsi

import (
	"encoding/json"
	"io/ioutil"
	"os"
	"path/filepath"
	"strings"

	"github.com/ghodss/yaml"
)

// Read one-liner text files, strip newline.
func slurpFile(path string) string {
	data, err := ioutil.ReadFile(path)
	if err != nil {
		return ""
	}

	return strings.TrimSpace(string(data))
}

// Write one-liner text files, add newline, ignore errors (best effort).
func spewFile(path string, data string, perm os.FileMode) {
	_ = ioutil.WriteFile(path, []byte(data+"\n"), perm)
}

func getDeviceDriver(pciAddr string) string {
	driverPath := filepath.Join("/sys/bus/pci/devices", pciAddr, "driver")

	if _, err := os.Stat(driverPath); err != nil {
		return ""
	}

	dest, err := os.Readlink(driverPath)
	if err != nil {
		return ""
	}
	return filepath.Base(dest)
}

// safeYAML returns a string after marshalling the supplied parameter into YAML
func SafeYAML(p interface{}) string {
	b, err := json.Marshal(p)
	if err != nil {
		return ""
	}
	yb, err := yaml.JSONToYAML(b)
	if err != nil {
		return ""
	}
	return string(yb)
}

// safeJSON returns a string after marshalling the supplied parameter into
// JSON. Accepts an optional argument to trigger pretty/indented formatting of
// the JSON string
func SafeJSON(p interface{}, indent bool) string {
	var b []byte
	var err error
	if !indent {
		b, err = json.Marshal(p)
	} else {
		b, err = json.MarshalIndent(&p, "", "  ")
	}
	if err != nil {
		return ""
	}
	return string(b)
}
